<template>
  <div
    v-loading="pageLoading"
    style="padding: 20px"
  >
    <el-breadcrumb
      v-if="detailInfo.isEdit"
      separator-class="el-icon-arrow-right"
    >
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章详情</el-breadcrumb-item>
    </el-breadcrumb>
    <div
      class="header"
      v-if="!detailInfo.isEdit"
    >
      <el-input
        style="width: 100%"
        v-model="title"
        placeholder="请输入文章标题..."
      ></el-input>
    </div>

    <Editor
      v-if="!detailInfo.isEdit"
      :value="value"
      :plugins="plugins"
      @change="handleChange"
      :locale="zhHans"
      :uploadImages="uploadImages"
    />

    <Viewer
      v-if="detailInfo.isEdit"
      :value="value"
      :plugins="plugins"
      :locale="zhHans"
    />

    <div
      class="footer"
      v-if="!detailInfo.isEdit"
    >
      <el-button
        type="primary"
        @click="onConfirm"
        >保存</el-button
      >
      <el-button @click="onClose">取消</el-button>
    </div>

    <el-drawer
      v-if="!detailInfo.isEdit"
      title="发布文章"
      :wrapperClosable="false"
      :visible.sync="drawer"
      :direction="direction"
      @open="onOpen"
      @before-close="beforeClose"
      custom-class="demo-drawer"
    >
      <div
        class="demo-drawer__content"
        style="padding: 20px"
      >
        <el-form
          ref="form"
          :model="form"
          label-width="80px"
          label-suffix=":"
          label-position="left"
        >
          <el-form-item
            label="标签"
            prop="tag"
            :rules="[{ required: true, message: '请选择', trigger: ['blur', 'change'] }]"
          >
            <el-select
              v-model="form.tag"
              placeholder="请选择"
              multiple
              :multiple-limit="2"
            >
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button @click="beforeClose">取 消</el-button>
            <el-button
              type="primary"
              @click="onSave"
              :loading="loading"
              >确定并发布</el-button
            >
          </el-form-item>
        </el-form>

        <!-- <div class="demo-drawer__footer"> -->
      </div>
    </el-drawer>

    <!--  -->

    <el-button-group
      class="fixed"
      v-if="detailInfo.isEdit"
    >
      <el-button
        @click="onPage('pre')"
        type="primary"
        icon="el-icon-arrow-left"
        >上一篇</el-button
      >
      <el-button
        @click="onPage('next')"
        type="primary"
        >下一篇<i class="el-icon-arrow-right el-icon--right"></i
      ></el-button>
    </el-button-group>
  </div>
</template>

<script>
// 这里就是引入所有的扩展的插件
import 'bytemd/dist/index.css' // 导入编辑器样式
import { Editor, Viewer } from '@bytemd/vue'
import gfm from '@bytemd/plugin-gfm'
import highlightssr from '@bytemd/plugin-highlight-ssr'
import highlight from '@bytemd/plugin-highlight'
import breaks from '@bytemd/plugin-breaks'
import footnotes from '@bytemd/plugin-footnotes'
import frontmatter from '@bytemd/plugin-frontmatter'
import gemoji from '@bytemd/plugin-gemoji'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import zhHans from 'bytemd/locales/zh_Hans.json'
import 'highlight.js/styles/vs.css'
import 'juejin-markdown-themes/dist/juejin.min.css' // 其实就是需要这个css文件

const tagList = [
  { name: 'js', id: 1 },
  { name: 'css', id: 2 },
  { name: 'Node.js', id: 3 },
  { name: '代码规范', id: 4 },
  { name: 'Vue', id: 5 },
  { name: 'React', id: 6 },
  { name: '数据库', id: 7 },
  { name: '面试', id: 8 },
  { name: '算法', id: 9 },
  { name: '架构', id: 10 },
]

const plugins = [
  gfm(),
  highlight(),
  highlightssr(),
  breaks(),
  frontmatter(),
  footnotes(),
  gemoji(),
  mediumZoom(),
  // Add more plugins here
]
export default {
  name: 'MyEditor',
  // name:'Editor',
  components: { Editor, Viewer },
  props: {},
  computed: {
    // detailInfo() {
    //   const info = this.$route.query
    //   return info
    // },
  },
  data() {
    return {
      pageLoading: false,
      article_id: null,
      zhHans,
      isEdit: false,
      drawer: false,
      direction: 'rtl', // 抽屉打开方式
      loading: false,
      title: '',
      value: '',
      plugins,
      form: {
        tag: '',
      },

      tagList,
      detailInfo: this.$route.query,
    }
  },
  methods: {
    async onOpen() {
      await this.$nextTick()
      this.$refs.form.resetFields()
    },

    beforeClose() {
      this.drawer = false
      this.$refs.form.resetFields()
    },

    async upload(files) {
      // console.log('上传的文件', files)
      const formData = new FormData()

      formData.append('file', files) // 这里替换成自己的上传地址，

      const res = await this.$axios.post('/api/file-upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })

      return res.data
    },

    async uploadImages(files) {
      console.log(files)
      // console.log('上传的文件',files)
      const imgs = []

      for (const file of files) {
        const key = await this.upload(file)
        console.log(key)

        imgs.push({
          title: key.name,
          url: key.imgUrl,
        })
      }

      return imgs
    },

    async onSave() {
      const valid = await this.$refs.form.validate()

      if (!valid) return

      const params = {
        title: this.title.trim() || '无标题',
        text: this.value,
        tags: this.form.tag.join(),
        user_name: this.$utils.getUserInfo(),
      }

      // console.log(params)
      this.loading = true
      const { code, message } = await this.$axios.post('api/add-article', params).catch(_ => _)
      this.loading = false

      if (code === 0) {
        this.$message.success('新增文章成功')
        this.onClose()
      } else this.$message.error(message || '保存失败')
    },

    handleChange(v) {
      this.value = v
    },

    async onConfirm() {
      // console.log(this.value)
      if (!this.value.trim()) {
        this.$message.error('不能新增空的文档')
        return
      }

      this.drawer = true
    },

    onClose() {
      this.$router.push('/home')
    },

    // 获取上一篇，或者下一篇文章
    async onPage(type) {
      // desc-降序 asce-升序
      const params = {
        page_type: type,
        id: this.article_id || this.detailInfo.article_id,
      }

      this.pageLoading = true
      const { code, data } = await this.$axios.post('/api/get-page', params).catch(_ => _)

      this.pageLoading = false
      if (code === 0) {
        this.value = data.text
        this.article_id = data.article_id
      }
    },
  },

  created() {
    this.value = this.detailInfo.text
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
    // }, 1500)
  },
}
</script>

<style
  lang="scss"
  scoped
>
::v-deep .bytemd {
  height: calc(100vh - 200px);
}
.footer {
  padding: 20px;
  text-align: center;
}

.fixed {
  position: fixed;
  right: 10px;
  bottom: 20px;
}
</style>
